<template>
  <div class="upload-container">
    <!-- 上传成功后显示的图片预览 -->
    <div v-if="imageUrl" class="image-preview-container">
      <img :src="imageUrl" alt="Uploaded image" class="preview-image" />
      <!-- 遮罩层 -->
      <div class="image-overlay" @click="triggerReplaceUpload">
        <!-- <button class="delete-button" @click.stop="handleImageRemove" title="delete image">
          <el-icon><CircleClose /></el-icon>
        </button> -->
        <div class="reupload">
          <svg
            width="27"
            height="27"
            viewBox="0 0 27 27"
            fill="none"
            xmlns="http://www.w3.org/2000/svg">
            <path
              fill-rule="evenodd"
              clip-rule="evenodd"
              d="M14.923 6.06323C15.1837 5.74133 15.6559 5.69169 15.9779 5.95236L18.4507 7.95485C18.7726 8.21552 18.8223 8.6878 18.5616 9.0097L16.5591 11.4826C16.2984 11.8045 15.8262 11.8541 15.5043 11.5934C15.1823 11.3328 15.1327 10.8605 15.3934 10.5386L16.2564 9.47287L7.6158 10.381C6.82531 10.4668 6.10081 10.8617 5.6004 11.4797C5.09998 12.0976 4.86431 12.8884 4.94479 13.6795L5.02306 14.4242C5.06636 14.8361 4.76751 15.2052 4.35557 15.2485C3.94362 15.2918 3.57457 14.9929 3.53128 14.581L3.45288 13.8351L3.45265 13.8329C3.33162 12.6472 3.68466 11.4619 4.43468 10.5357C5.18469 9.6095 6.27074 9.01772 7.45562 8.8896L7.45785 8.88937L16.0996 7.98108L15.0339 7.11808C14.712 6.85741 14.6623 6.38514 14.923 6.06323ZM22.0218 11.1293C22.4337 11.086 22.8028 11.3848 22.8461 11.7968L22.9245 12.5427L22.9247 12.5449C23.0457 13.7305 22.6927 14.9159 21.9427 15.8421C21.1926 16.7683 20.1066 17.3601 18.9217 17.4882L18.9195 17.4884L10.2777 18.3967L11.3435 19.2597C11.6654 19.5204 11.715 19.9926 11.4543 20.3145C11.1937 20.6364 10.7214 20.6861 10.3995 20.4254L7.92662 18.4229C7.60471 18.1622 7.55508 17.69 7.81575 17.3681L9.81823 14.8952C10.0789 14.5733 10.5512 14.5237 10.8731 14.7843C11.195 15.045 11.2446 15.5173 10.984 15.8392L10.121 16.9049L18.7616 15.9967C19.5521 15.911 20.2765 15.516 20.7769 14.8981C21.2774 14.2801 21.5131 13.4893 21.4325 12.6982L21.3543 11.9536C21.311 11.5416 21.6098 11.1726 22.0218 11.1293Z"
              fill="white" />
          </svg>

          <div class="overlay-text"></div>
        </div>
      </div>
    </div>

    <!-- 上传组件，仅在没有图片时显示 -->
    <el-upload
      v-else
      class="upload-el"
      drag
      :show-file-list="false"
      :file-list="fileList"
      :http-request="handleCustomUpload"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :limit="1"
      accept="image/*">
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg">
        <path
          d="M12.0059 2C12.558 2.0002 13.0059 2.44784 13.0059 3V10.999H21.0049C21.557 10.999 22.0047 11.4469 22.0049 11.999C22.0049 12.5513 21.5572 12.999 21.0049 12.999H13.0059V21.0098C13.0059 21.5619 12.558 22.0096 12.0059 22.0098C11.4536 22.0098 11.0059 21.562 11.0059 21.0098V12.999H2.99512C2.44283 12.999 1.99512 12.5513 1.99512 11.999C1.99531 11.4469 2.44295 10.999 2.99512 10.999H11.0059V3C11.0059 2.44772 11.4536 2 12.0059 2Z"
          fill="#CBCBCB" />
      </svg>

      <!-- <SvgIcon name="ai-upload" size="24" /> -->
      <!-- <div class="el-upload__text"></div> -->
      <div class="el-upload__tip"></div>
    </el-upload>

    <!-- 隐藏的文件输入，用于触发重新上传 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleFileChange" />
  </div>
</template>

<script setup lang="ts">
  import { ref, defineEmits, defineProps, computed } from 'vue';
  import { UploadFile, UploadRawFile } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import { BaseAPI } from '@/api/base';

  // 定义组件接收的 props
  const props = defineProps<{
    modelValue?: string;
  }>();

  // 定义组件发送的事件
  const emit = defineEmits<{
    'update:modelValue': [value: string];
    'upload-success': [file: UploadFile, response: any];
    'upload-error': [error: any];
  }>();

  // 文件列表状态
  const fileList = ref<UploadFile[]>([]);
  const uploadLoading = ref(false);
  const fileInputRef = ref<HTMLInputElement>();

  // 从props计算当前图片URL
  const imageUrl = computed(() => props.modelValue);

  // 文件上传前的验证方法
  const beforeUpload = (file: UploadRawFile) => {
    // 定义最大文件大小 (20MB)
    const maxSize = 20 * 1024 * 1024;

    // 检查文件大小
    if (file.size && file.size > maxSize) {
      ElMessage.error('The file size cannot exceed 20M');
      return false;
    }

    // 验证通过，继续上传
    return true;
  };

  // 自定义上传方法
  const handleCustomUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;

    try {
      uploadLoading.value = true;

      // 调用实际的文件上传接口
      const response = await BaseAPI.uploadFile(file);

      // 假设响应中包含文件的URL
      const fileUrl = response.data.url;

      // 更新文件列表
      fileList.value = [
        {
          name: file.name,
          url: fileUrl,
          uid: file.uid || `file_${Date.now()}`,
          raw: file,
          status: 'ready',
        },
      ];

      // 通知父组件更新图片URL
      emit('update:modelValue', fileUrl);
      emit('upload-success', fileList.value[0], response);

      // 通知组件上传成功
      onSuccess(response);
    } catch (error) {
      // 通知组件上传失败
      onError(error);
      emit('upload-error', error);
      console.error('文件上传失败:', error);
    } finally {
      uploadLoading.value = false;
    }
  };

  // 处理文件删除
  const handleRemove = (file: UploadFile) => {
    const index = fileList.value.findIndex((item) => item.uid === file.uid);
    if (index !== -1) {
      fileList.value.splice(index, 1);
      // 通知父组件清除图片URL
      emit('update:modelValue', '');
    }
    return true;
  };

  // 处理图片删除（从预览区域）
  const handleImageRemove = () => {
    fileList.value = [];
    emit('update:modelValue', '');
  };

  // 触发替换上传
  const triggerReplaceUpload = () => {
    fileInputRef.value?.click();
  };

  // 处理文件选择变化（替换上传）
  const handleFileChange = async (event: Event) => {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];

      // 先验证文件
      if (!beforeUpload(file as UploadRawFile)) {
        // 重置input，允许再次选择同一个文件
        input.value = '';
        return;
      }

      // 构造上传选项
      const uploadOptions = {
        file,
        onSuccess: () => {},
        onError: () => {},
      };

      // 执行上传
      await handleCustomUpload(uploadOptions);

      // 重置input，允许再次选择同一个文件
      input.value = '';
    }
  };
</script>

<style lang="scss" scoped>
  .upload-container {
    position: relative;
    width: 80px;
    height: 120px;
    transform: rotate(-6deg);
    transition: transform 0.3s ease;
  }

  .upload-el {
    height: 100%;
    border: 1px solid #e1e2e3;
    border-radius: 8px;
    overflow: hidden;
    background: #f8f8f8;
    &:hover {
      background: #ededed;
    }
    :deep(.el-upload-dragger) {
      border-radius: 0px;
      border: none;
      outline: none;
      height: 120px;
      background: transparent;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }

    .el-upload__text {
      font-size: 16px;
      color: #f8f8f8;
      font-weight: 600;

      line-height: 100%;
      margin: 4px 0px;
    }
    .el-upload__tip {
      font-size: 14px;
      color: #cbcbcb;
      font-weight: 400;

      line-height: 100%;
    }
  }

  // 图片预览容器样式
  .image-preview-container {
    position: relative;
    height: 120px; // 可根据需要调整高度
    overflow: hidden;
    background: #404040;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #f76b1b;
  }

  // 预览图片样式
  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  // 遮罩层样式
  .image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
  }

  // 鼠标悬浮时显示遮罩层
  .image-preview-container:hover .image-overlay {
    opacity: 1;
  }

  .reupload {
    display: flex;
    flex-direction: column;
    align-items: center;

    // 遮罩层提示文本样式
    .overlay-text {
      font-weight: 600;
      font-style: SemiBold;
      font-size: 16px;
      line-height: 100%;
      letter-spacing: 0%;
      text-align: right;
      margin-top: 8px;
      text-decoration: underline;
    }
  }
  // 删除按钮样式
  .delete-button {
    position: absolute;
    top: 8px;
    right: 8px;
    background-color: rgba(255, 255, 255, 0.2);
    border: none;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
    transition: background-color 0.3s ease;
    z-index: 1;

    &:hover {
      background-color: rgba(255, 255, 255, 0.3);
    }
  }
</style>
